/**
 * 任务状态本地管理 Composable
 * 用于管理用户的任务完成状态，数据存储在本地localStorage中
 */
import { ref, computed } from 'vue'
import type { TaskStatus } from '@/types/task-flow'

// 本地存储的键名
const STORAGE_KEY = 'task_status_local'

// 任务状态数据结构
interface TaskStatusData {
  [flowId: string]: {
    [nodeId: string]: {
      status: TaskStatus
      updatedAt: string
    }
  }
}

// 全局状态
const taskStatusData = ref<TaskStatusData>({})
const isLoaded = ref(false)

export function useTaskStatus() {
  
  // 加载本地存储的数据
  const loadLocalData = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        taskStatusData.value = JSON.parse(stored)
      }
      isLoaded.value = true
      console.log('本地任务状态数据加载完成:', taskStatusData.value)
    } catch (error) {
      console.error('加载本地任务状态失败:', error)
      taskStatusData.value = {}
      isLoaded.value = true
    }
  }

  // 保存数据到本地存储
  const saveLocalData = () => {
    try {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(taskStatusData.value))
      console.log('本地任务状态数据已保存')
    } catch (error) {
      console.error('保存本地任务状态失败:', error)
    }
  }

  // 获取指定任务的状态
  const getTaskStatus = (flowId: string, nodeId: string): TaskStatus | null => {
    if (!isLoaded.value) {
      loadLocalData()
    }

    // 确保参数有效
    if (!flowId || !nodeId) return null

    const flowData = taskStatusData.value[flowId]
    if (!flowData) return null

    const nodeData = flowData[nodeId]
    if (!nodeData) return null

    return nodeData.status
  }

  // 设置指定任务的状态
  const setTaskStatus = (flowId: string, nodeId: string, status: TaskStatus) => {
    if (!isLoaded.value) {
      loadLocalData()
    }

    // 确保参数有效
    if (!flowId || !nodeId || !status) {
      console.error('设置任务状态失败：参数无效', { flowId, nodeId, status })
      return
    }

    // 确保流程图数据存在
    if (!taskStatusData.value[flowId]) {
      taskStatusData.value[flowId] = {}
    }

    // 设置任务状态
    taskStatusData.value[flowId][nodeId] = {
      status,
      updatedAt: new Date().toISOString()
    }

    // 保存到本地存储
    saveLocalData()

    console.log(`任务状态已更新: ${flowId}/${nodeId} -> ${status}`)
  }

  // 获取流程图的所有任务状态
  const getFlowTaskStatuses = (flowId: string) => {
    if (!isLoaded.value) {
      loadLocalData()
    }
    
    return taskStatusData.value[flowId] || {}
  }

  // 重置流程图的所有任务状态
  const resetFlowStatuses = (flowId: string) => {
    if (!isLoaded.value) {
      loadLocalData()
    }

    delete taskStatusData.value[flowId]
    saveLocalData()
    
    console.log(`流程图 ${flowId} 的任务状态已重置`)
  }

  // 获取流程图的进度统计
  const getFlowProgress = (flowId: string, totalNodes: number) => {
    if (!isLoaded.value) {
      loadLocalData()
    }

    const flowData = taskStatusData.value[flowId] || {}
    const statuses = Object.values(flowData)
    
    const completed = statuses.filter(item => item.status === 'completed').length
    const inProgress = statuses.filter(item => item.status === 'in-progress').length
    const blocked = statuses.filter(item => item.status === 'blocked').length
    const pending = totalNodes - completed - inProgress - blocked
    
    return {
      total: totalNodes,
      completed,
      inProgress,
      blocked,
      pending,
      completedPercentage: totalNodes > 0 ? Math.round((completed / totalNodes) * 100) : 0
    }
  }

  // 导出数据
  const exportData = () => {
    if (!isLoaded.value) {
      loadLocalData()
    }
    
    return {
      data: taskStatusData.value,
      exportedAt: new Date().toISOString(),
      version: '1.0'
    }
  }

  // 导入数据
  const importData = (data: any) => {
    try {
      if (data && data.data && typeof data.data === 'object') {
        taskStatusData.value = data.data
        saveLocalData()
        console.log('任务状态数据导入成功')
        return true
      } else {
        console.error('导入数据格式错误')
        return false
      }
    } catch (error) {
      console.error('导入任务状态数据失败:', error)
      return false
    }
  }

  // 清空所有数据
  const clearAllData = () => {
    taskStatusData.value = {}
    saveLocalData()
    console.log('所有任务状态数据已清空')
  }

  // 计算属性：是否有任何数据
  const hasAnyData = computed(() => {
    return Object.keys(taskStatusData.value).length > 0
  })

  // 初始化时加载数据
  if (!isLoaded.value) {
    loadLocalData()
  }

  return {
    // 状态
    isLoaded,
    hasAnyData,
    
    // 方法
    getTaskStatus,
    setTaskStatus,
    getFlowTaskStatuses,
    resetFlowStatuses,
    getFlowProgress,
    exportData,
    importData,
    clearAllData,
    loadLocalData,
    saveLocalData
  }
}
